package com.jacen.fzxs.controller;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jacen.fzxs.entity.ImageEntity;
import com.jacen.fzxs.entity.WallEntity;
import com.jacen.fzxs.service.IImageService;
import com.jacen.fzxs.service.IWallService;
import com.jacen.fzxs.util.DateUtils;
import com.jacen.fzxs.util.EntityUtils;
import com.jacen.fzxs.util.ServletUtils;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 文件上传
 * @author Jacen
 *
 */
@Controller
public class UploadController extends BaseController {
	
	@Resource
	private IWallService wallService;
	@Resource
	private IImageService imageService;
	
	/**
	 * 图片默认高度
	 */
	private int IMG_HEIGHT = 1080;
	/**
	 * 图片默认宽度
	 */
	private int IMG_WIDTH = 1920;
	
	/**
	 * linux 图片保存路径
	 */
//	public static final String UPLOAD_PATH = "/upload/";
//	public static final String UPLOAD_PATH_TEMP = "/upload/temp/";
	/**
	 * windows 图片保存路径
	 */
	public static final String UPLOAD_PATH = "d:/upload/";
	public static final String UPLOAD_PATH_TEMP = "d:/upload/temp/";
	
	public void setIMG_HEIGHT(int iMG_HEIGHT) {
		IMG_HEIGHT = iMG_HEIGHT;
	}


	public void setIMG_WIDTH(int iMG_WIDTH) {
		IMG_WIDTH = iMG_WIDTH;
	}

	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
	
	/**
	 * 进入批量上传页面
	 * @param request
	 * @param paths
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/enterBatchUpload.do",method = RequestMethod.GET )
 	public String enterBatchUpload(HttpServletRequest request,String paths) throws Exception{
		logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户："+getLocalUser(request).getUserName()+"进入批量上传图片界面");
 		return "wall/batchUpload";
 	}
	
	
	/**
	 * 批量上传
	 * @param request
	 * @param response
	 */
 	@RequestMapping("/batchUpload.do" )
 	public void upload(HttpServletRequest request,HttpServletResponse response) {
 		MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;

		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		StringBuffer path = new StringBuffer(UPLOAD_PATH);
		File tempDir = new File(UPLOAD_PATH_TEMP);//源文件存放
		if(!tempDir.exists()) tempDir.mkdir();
		File uploadDir = new File(path.toString());
		if (!uploadDir.exists()) uploadDir.mkdir();
		String fileName = null;
		String username = "";
		String tel ="";
		ImageEntity imageEntity = null;
		for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
			MultipartFile mf = entry.getValue();
			fileName = mf.getOriginalFilename();
			//获取WallEntity
			try{
 	 			username = fileName.split("@")[0];
 	 			tel = fileName.split("@")[1];
 	 			WallEntity entity = wallService.getEntity(username,tel);
 	 			if(entity!=null){
 	 				//创建wid文件夹
 	 				path.append(entity.getId());
 	 				File wallDir = new File(path.toString());
 	 				if (!wallDir.exists()) wallDir.mkdir();
 	 				File uploadFile = new File(path.toString()+"/" + fileName);
 	 				File temp = new File(UPLOAD_PATH_TEMP+fileName);
 	 				//拷贝文件
 	 				FileCopyUtils.copy(mf.getBytes(), temp);
 					resize(ImageIO.read(temp), uploadFile);
 					imageEntity = new ImageEntity();
 					imageEntity.setId(EntityUtils.createId32());
 					//imageEntity.setSize(uploadFile.getTotalSpace());
 					imageEntity.setUrl("/images/"+entity.getId()+"/"+fileName);
 					imageEntity.setName(fileName);
 					imageEntity.setWid(entity.getId());
 					imageEntity.setExt(fileName.substring(fileName.indexOf(".")));
 					imageService.insert(imageEntity);
 					wallService.update(entity);
 					ServletUtils.outputMsgInJson(response, 0, "上传成功");
 					logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户："+getLocalUser(request).getUserName()+"上传图片："+fileName);
 	 			}else{
 	 				ServletUtils.outputMsgInJson(response, 1, "找不到该用户的墙体");
 	 			}
 			}catch(Exception e){
 				logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户："+getLocalUser(request).getUserName()+"批量上传图片发生异常："+e.getLocalizedMessage());
 				ServletUtils.outputMsgInJson(response, 1, "文件名称异常");
 			}
			
		}
	}
 	
 	/**
 	 * 上传图片
 	 * @param wid
 	 * @param request
 	 * @param response
 	 */
	@RequestMapping("/uploadImages.do")
 	public void upload(String wid,HttpServletRequest request,HttpServletResponse response) {
 		MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
 		WallEntity entity = wallService.getById(wid);

		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		StringBuffer path = new StringBuffer(UPLOAD_PATH);
		File tempDir = new File(UPLOAD_PATH_TEMP);//源文件存放
		if(!tempDir.exists()) tempDir.mkdir();
		File uploadDir = new File(path.toString());
		if (!uploadDir.exists()) uploadDir.mkdir();
		path.append(entity.getId());
		File wallDir = new File(path.toString());
		if (!wallDir.exists()) wallDir.mkdir();
		ImageEntity imageEntity = null;
		String fileName = null;
		for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
			MultipartFile mf = entry.getValue();
			fileName = mf.getOriginalFilename();
			File uploadFile = new File(path.toString()+"/" + fileName);
			File temp = new File(UPLOAD_PATH_TEMP+fileName);
			imageEntity = new ImageEntity();
			try {
				FileCopyUtils.copy(mf.getBytes(), temp);
				resize(ImageIO.read(temp), uploadFile);
				imageEntity.setId(EntityUtils.createId32());
				//imageEntity.setSize(uploadFile.getTotalSpace());
				imageEntity.setUrl("/images/"+entity.getId()+"/"+fileName);
				imageEntity.setName(fileName);
				imageEntity.setWid(wid);
				imageEntity.setExt(fileName.substring(fileName.indexOf(".")));
				imageService.insert(imageEntity);
				//wallService.update(entity);
				logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户："+getLocalUser(request).getUserName()+"上传图片："+fileName);
				ServletUtils.outputMsgInJson(response, 0,entity.getImages());
			} catch (Exception e) {
				ServletUtils.outputMsgInJson(response, 1, "上传失败");
				logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户："+getLocalUser(request).getUserName()+"上传图片发生异常："+e.getLocalizedMessage());
			}
		}
	}
	
	/**
	 * 图片压缩
	 * @param img 要压缩的图片
	 * @param uploadFile 输出文件
	 * @throws IOException
	 */
	public void resize(Image img,File uploadFile) throws IOException {  
		    
	        // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢  
	        BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,BufferedImage.TYPE_INT_RGB );   
	        image.getGraphics().drawImage(img, 0, 0, IMG_WIDTH, IMG_HEIGHT, null); // 绘制缩小后的图  
	        FileOutputStream out = new FileOutputStream(uploadFile); // 输出到文件流  
	        // 可以正常实现bmp、png、gif转jpg  
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
	        encoder.encode(image); // JPEG编码  
	        out.close();  
	   }  

}
